package com.education.wisdom.controller.management;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.education.common.poi.POIUtils;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.wisdom.pojo.Catalog;
import com.education.wisdom.pojo.CatalogAppraisal;
import com.education.wisdom.pojo.Paper;
import com.education.wisdom.pojo.Questions;
import com.education.wisdom.service.*;
import com.education.wisdom.vo.PaperVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/Manage")
public class PaperController {


    @Autowired
    private IPaperService paperService;

    @Autowired
    private IQuestionsService questionsService;

    @Autowired
    private MsPaperQuestionService paperQuestionService;

    @Autowired
    private ICatalogService catalogService;

    @Autowired
    private ICatalogAppraisalService catalogAppraisalService;

    @GetMapping("/paper/findById")
    public ApiReturnObject findById(Integer paperId) {
        int j = 1;
        Paper paper = paperService.selectPaperById(paperId);
        //1 单选 2 判断 3 多选 4 简答
        List<Questions> squestionsList = questionsService.selectByPaperId(paperId, 1);
        for (Questions aSquestionsList : squestionsList) {
            aSquestionsList.setNum(j);
            j++;
        }
        paper.setSinglList(squestionsList);
        List<Questions> jquestionsList = questionsService.selectByPaperId(paperId, 2);
        for (Questions aJquestionsList : jquestionsList) {
            aJquestionsList.setNum(j);
            j++;
        }
        paper.setJudgeList(jquestionsList);
        List<Questions> mquestionsList = questionsService.selectByPaperId(paperId, 3);
        for (int i = 0; i < mquestionsList.size(); i++) {
            mquestionsList.get(i).setNum(j);
            j++;
        }
        paper.setManList(mquestionsList);
        List<Questions> aquestionsList = questionsService.selectByPaperId(paperId, 4);
        for (int i = 0; i < aquestionsList.size(); i++) {
            aquestionsList.get(i).setNum(j);
            j++;
        }
        paper.setAnsList(aquestionsList);
//        paper.setStartTimeStr(DateUtils.formatDate(paper.getStartTime()));
//        paper.setEndTimeStr(DateUtils.formatDate(paper.getEndTime()));
        return new ApiReturnObject("200", "操作成功", paper);
    }

    /**
     * 试卷查询
     *
     * @return
     */
    @GetMapping("/Paper/List")
    public ApiReturnObject paperList(Integer rCatalogid, Integer pageNum, Integer pageSize, Integer appraisalCatalogId) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("catalogId", rCatalogid);
        map.put("appraisalCatalogId", appraisalCatalogId);
        List<Paper> paperList = paperService.selectPaperList(map);
        ArrayList<PaperVo> list = new ArrayList<>();
        for (Paper paper : paperList) {
            PaperVo paperVo = new PaperVo();
            if (paper.getCatalogId() != null) {
                //查询目录名称
                Catalog catalog = catalogService.selectByCatalogId2(paper.getCatalogId());
                if (catalog != null) {
                    paper.setParentName(catalog.getName());
                }
            }
            //查询试题id
//            String[] array = paperQuestionService.selectByQuestionids(paper.getId());
//            paper.setQuestionIds(array);
            //1 单选 2 判断 3 多选 4 简答
            String[] sing = paperQuestionService.selectByPaperIdAndType(paper.getId(), 1);
            paperVo.setSingleList(append(sing));
            String[] many = paperQuestionService.selectByPaperIdAndType(paper.getId(), 3);
            paperVo.setManyList(append(many));
            String[] judg = paperQuestionService.selectByPaperIdAndType(paper.getId(), 2);
            paperVo.setJudgmentList(append(judg));
            String[] answ = paperQuestionService.selectByPaperIdAndType(paper.getId(), 4);
            paperVo.setAnswList(append(answ));

            String[] arr = {paper.getSjType()};
            paper.setSjTypearray(arr);
            String[] arr1 = {paper.getSjLevel()};
            paper.setSjLevelarray(arr1);
            String[] arr2 = {paper.getDelFlag()};
            paper.setDelFlagarray(arr2);

            if (!"0".equals(paper.getAppraisalCatalogId())) {
                CatalogAppraisal appraisal = catalogAppraisalService.selectCatalogAppraisalByCatalogId(paper.getAppraisalCatalogId());
                if (StringUtils.isNotNull(appraisal)) { paper.setParentName(appraisal.getName()); }
            }else {
                List<Catalog> catalogs = catalogService.selectByCatalogId(paper.getCatalogId());
                if (StringUtils.isNotEmpty(catalogs)) { paper.setParentName(catalogs.get(0).getName()); }
            }

            BeanUtils.copyProperties(paper, paperVo);
            list.add(paperVo);
        }
        return new ApiReturnObject("200", "操作成功", new PageInfo<PaperVo>(list));
    }

    private String append(String[] array) {
        if (StringUtils.isNotEmpty(array)) {
            StringBuilder builder = new StringBuilder();
            for (String s : array) {
                builder.append(s).append(",");
            }
            String s = builder.toString();
            return s.substring(0, s.length() - 1);
        }
        return null;
    }

    /**
     * 专业课程体系
     *
     * @param paper
     * @return
     */
    @PostMapping("/Paper/ins")
    public ApiReturnObject ins(@RequestBody PaperVo paper) {
        paper.setCreateTime(new Date());
        int i = paperService.insertPaper(paper);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }


    /**
     * 职业技能测试
     *
     * @param paper
     * @return
     */
    @PostMapping("/test/ins")
    @SuppressWarnings("all")
    public ApiReturnObject insert(@RequestBody PaperVo paper) {
        int length, sing, many, judg, answ;

        if (StringUtils.isNotEmpty(paper.getSjTypearray())) { paper.setSjType(paper.getSjTypearray()[0]); }
        if (StringUtils.isNotEmpty(paper.getSjLevelarray())) { paper.setSjLevel(paper.getSjLevelarray()[0]); }
        if (StringUtils.isNotEmpty(paper.getDelFlagarray())) { paper.setDelFlag(paper.getDelFlagarray()[0]); }
//        //校验ip
//      if (StringUtil.isNotEmpty(paper.getIpStart()) && StringUtil.isNotEmpty(paper.getIpEnd())) {
//           if (IPAddressUtil.isIPv4LiteralAddress(paper.getIpStart()) && IPAddressUtil.isIPv4LiteralAddress(paper.getIpStart())){
//               paper.setIp(paper.getIpStart() + "-" + paper.getIpEnd());
//           }else {
//               return new ApiReturnObject("201","ip不规范","ip不规范");
//           }
//        }
//
//        if (StringUtil.isEmpty(paper.getIp())){
//            return new ApiReturnObject("201","ip不存在","ip不存在");
//        }
        paper.setCreateTime(new Date());
        //2 随机出题 1 手动出题
        if ("2".equals(paper.getDelFlag())) {
            //1 单选 2 判断 3 多选 4 简答
            length = (sing = paper.getSingle()) + (many = paper.getMany()) + (judg = paper.getJudgment()) + (answ = paper.getAnsw());
            String[] array = new String[length];
            String[] sinIds = questionsService.selectIdsByTypeCatalog(1,paper.getAppraisalCatalogId());
            String[] judgIds = questionsService.selectIdsByTypeCatalog(2,paper.getAppraisalCatalogId());
            String[] manyIds = questionsService.selectIdsByTypeCatalog(3,paper.getAppraisalCatalogId());
            String[] answIds = questionsService.selectIdsByTypeCatalog(4,paper.getAppraisalCatalogId());
            if(sinIds.length == 0 || sing > sinIds.length){ return new ApiReturnObject("201", "该课程单选题数量不足", ""); }
            if(judgIds.length == 0 || many > judgIds.length){ return new ApiReturnObject("201", "该课程多选题数量不足", ""); }
            if(manyIds.length == 0 || judg > manyIds.length){ return new ApiReturnObject("201", "该课程判断题数量不足", ""); }
            if(answIds.length == 0 || answ > answIds.length){ return new ApiReturnObject("201", "该课程简答题数量不足", ""); }

            for (int i = 0; i < length; i++) {
                Random random = new Random();
                if(i < sing){
                    //根据选择的单选题个数 往数组中添加查询出的单选题id
                    int i1 = random.nextInt(sinIds.length);
                    array[i] = sinIds[i1];
                }else if(i < sing + many){
                    //根据选择的单选题和多选题个数 往数组中添加查询出的多选题id
                    int i3 = random.nextInt(manyIds.length);
                    array[i] = manyIds[i3];
                }else  if(i < sing + many + judg){
                    //根据选择的单选题和多选题和判断题个数 往数组中添加查询出的判断题id
                    int i2 = random.nextInt(judgIds.length);
                    array[i] = judgIds[i2];
                }else{
                    //根据选择的单选题和多选题和判断题和简答题个数 往数组中添加查询出的简答题id
                    int i4 = random.nextInt(answIds.length);
                    array[i] = answIds[i4];
                }
            }

            for (String s : array) {
                if(s==null){
                    return new ApiReturnObject("201", "无试题", "");
                }
            }
            paper.setQuestionIds(array);
        }else {
            //把数组整合到一起
            String[] signarr = StringUtils.isNotEmpty(paper.getSingleList()) ? paper.getSingleList().split(",") : new String[0];//单选
            String[] manyarr = StringUtils.isNotEmpty(paper.getManyList()) ? paper.getManyList().split(",") : new String[0];//多选
            String[] judgarr = StringUtils.isNotEmpty(paper.getJudgmentList()) ? paper.getJudgmentList().split(",") : new String[0];//判断
            String[] answarr = StringUtils.isNotEmpty(paper.getAnswList()) ? paper.getAnswList().split(",") : new String[0];//简答
            length = (sing = signarr.length) + (many = manyarr.length) + (judg = judgarr.length) + (answ = answarr.length);
            String[] array = new String[length];//保存id
            System.arraycopy(signarr, 0, array, 0, sing);
            System.arraycopy(manyarr, 0, array, sing, many);
            System.arraycopy(judgarr, 0, array, many + sing, judg);
            System.arraycopy(answarr, 0, array, many + sing + judg, answ);
            paper.setQuestionIds(array);
        }
        int i = paperService.insertPaperTest(paper);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    /**
     * 职业技能测试
     *
     * @param paper
     * @return
     */
    @PostMapping("/test/update")
    public ApiReturnObject testUpdate(@RequestBody PaperVo paper) {
        int length, sing, many, judg, answ;

        if (StringUtils.isNotEmpty(paper.getSjTypearray())){ paper.setSjType(paper.getSjTypearray()[0]); }
        if (StringUtils.isNotEmpty(paper.getSjLevelarray())){ paper.setSjLevel(paper.getSjLevelarray()[0]); }
        if (StringUtils.isNotEmpty(paper.getDelFlagarray())){ paper.setDelFlag(paper.getDelFlagarray()[0]); }

        paper.setCreateTime(new Date());
        //2 随机出题 1 手动出题
        if ("2".equals(paper.getDelFlag())) {
            //1 单选 2 判断 3 多选 4 简答
            length = (sing = paper.getSingle()) + (many = paper.getMany()) + (judg = paper.getJudgment()) + (answ = paper.getAnsw());
            String[] array = new String[length];
            String[] sinIds = questionsService.selectIdsByType(1);
            String[] judgIds = questionsService.selectIdsByType(2);
            String[] manyIds = questionsService.selectIdsByType(3);
            String[] answIds = questionsService.selectIdsByType(4);
            for (int i = 0; i < length; i++) {
                Random random = new Random();
                int i1 = random.nextInt(sinIds.length);
                int i2 = random.nextInt(judgIds.length);
                int i3 = random.nextInt(manyIds.length);
                int i4 = random.nextInt(answIds.length);
                if (i < sing){ array[i] = sinIds[i1]; }
                if (i >= sing && i < sing + many){ array[i] = manyIds[i3]; }
                if (i >= sing + many && i < sing + many + judg){ array[i] = judgIds[i2]; }
                if (i >= sing + many + judg && i < sing + many + judg + answ){ array[i] = answIds[i4]; }
            }
            paper.setQuestionIds(array);
        }
        if ("1".equals(paper.getDelFlag())) {
            //把数组整合到一起
            String[] signarr = StringUtils.isNotEmpty(paper.getSingleList()) ? paper.getSingleList().split(",") : new String[0];//单选
            String[] manyarr = StringUtils.isNotEmpty(paper.getManyList()) ? paper.getManyList().split(",") : new String[0];//多选
            String[] judgarr = StringUtils.isNotEmpty(paper.getJudgmentList()) ? paper.getJudgmentList().split(",") : new String[0];//判断
            String[] answarr = StringUtils.isNotEmpty(paper.getAnswList()) ? paper.getAnswList().split(",") : new String[0];//简答
            length = (sing = signarr.length) + (many = manyarr.length) + (judg = judgarr.length) + (answ = answarr.length);
            String[] array = new String[length];//保存id
            System.arraycopy(signarr, 0, array, 0, sing);
            System.arraycopy(manyarr, 0, array, sing, many);
            System.arraycopy(judgarr, 0, array, many + sing, judg);
            System.arraycopy(answarr, 0, array, many + sing + judg, answ);
            paper.setQuestionIds(array);
        }
        int i = paperService.updatePaperTest(paper);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    @PostMapping("/Paper/update")
    public ApiReturnObject update(@RequestBody PaperVo paper) {
        int i = paperService.updatePaper(paper);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    @GetMapping("/Paper/delete")
    public ApiReturnObject delete(String ids) {
        int i = paperService.deletePaperByIds(ids);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }


    /**
     * 试题
     * @param questions
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/Question/List")
    public ApiReturnObject list(Questions questions, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
//        questions.setQuestionType("1");
        List<Questions> questionsList = questionsService.selectQuestionsList(questions);
        for (Questions ques : questionsList) {
            String[] arr = {ques.getStType()};
            ques.setCheckList(arr);
            if (questions.getType() == 1) {
                CatalogAppraisal appraisal = catalogAppraisalService.selectCatalogAppraisalByCatalogId(ques.getCatalogId());
                if (StringUtils.isNotNull(appraisal)){ ques.setParentName(appraisal.getName()); }
            } else {
                List<Catalog> catalogs = catalogService.selectByCatalogId(ques.getCatalogId());
                if (StringUtils.isNotEmpty(catalogs)){ ques.setParentName(catalogs.get(0).getName()); }
            }
        }
        return new ApiReturnObject("200", "操作成功", new PageInfo<Questions>(questionsList));
    }

    @GetMapping("/question/findQuestByType")
    public ApiReturnObject findQuestByType(String type, String name,Integer catalogId) {
        Questions questions = new Questions();
        questions.setQuestionType(type);
        questions.setStContent(name);
        questions.setCatalogId(catalogId);
        List<Questions> questionsList = questionsService.selectQuestionsList(questions);
        return new ApiReturnObject("200", "操作成功", questionsList);
    }

    @GetMapping("/Question/delete")
    public ApiReturnObject deleteQuestion(String ids) {
        int i = questionsService.deleteQuestionsByIds(ids);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    @PostMapping("/Question/ins")
    public ApiReturnObject ins(@RequestBody Questions questions) {
        questions.setStType(questions.getCheckList()[0]);
        questions.setCreateTime(new Date());
        int i = questionsService.insertQuestions(questions);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    @PostMapping("/Question/update")
    public ApiReturnObject updateQuestion(@RequestBody Questions questions) {
        if (questions.getCheckList() != null){ questions.setStType(questions.getCheckList()[0]); }
        int i = questionsService.updateQuestions(questions);
        if (i > 0) {
            return new ApiReturnObject("200", "操作成功", "");
        }
        return new ApiReturnObject("201", "操作失败", "");
    }

    /**
     * 专业课程试题导入
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/Question/import")
    @Transactional
    public ApiReturnObject importQuestion(MultipartFile file) throws IOException {
        //读取execle数据
        List<String[]> strings = POIUtils.readExcel(file);
        for (String[] string : strings) {
            Questions questions = new Questions();
            questions.setCreateTime(new Date());
            questions.setStContent(string[0]);
            questions.setStSelecta(string[1]);
            questions.setStSelectb(string[2]);
            questions.setStSelectc(string[3]);
            questions.setStSelectd(string[4]);
            questions.setStSelecte(string[5]);
            questions.setStAnswer(string[6]);
//            String s = StringUtil.isEmpty(string[8]) ? "0" : string[8];
//            questions.setStScore(new BigDecimal(s));
            questions.setStType(string[7]);
            questions.setQuestionType(string[8]);
            questions.setStAnalysis(string[9]);
            //目录名称 根据目录名称查询 catalogId
            String catalogName = string[10];
            Catalog catalog = new Catalog();
            catalog.setName(catalogName);
            List<Catalog> catalogs = catalogService.selectCatalogListByName(catalog);
            if(catalogs.size() > 0){
                Integer catalogId = catalogs.get(0).getCatalogId();
                questions.setCatalogId(catalogId);
                questionsService.insertQuestions(questions);
            }else {
                return new ApiReturnObject("201", catalogName + " 目录名称无效，请修改后重新上传", "");
            }
        }
        return new ApiReturnObject("200", "操作成功", "");
    }


    /**
     * 职业技能试题导入
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/Question/importBySkill")
    @Transactional
    public ApiReturnObject importQuestionBySkill(MultipartFile file) throws IOException {
        //读取execle数据
        List<String[]> strings = POIUtils.readExcel(file);
        for (String[] string : strings) {
            Questions questions = new Questions();
            questions.setCreateTime(new Date());
            questions.setStContent(string[0]);
            questions.setStSelecta(string[1]);
            questions.setStSelectb(string[2]);
            questions.setStSelectc(string[3]);
            questions.setStSelectd(string[4]);
            questions.setStSelecte(string[5]);
            questions.setStAnswer(string[6]);
//            String s = StringUtil.isEmpty(string[8]) ? "0" : string[8];
//            questions.setStScore(new BigDecimal(s));
            questions.setStType(string[7]);
            questions.setQuestionType(string[8]);
            questions.setStAnalysis(string[9]);
            //目录名称 根据目录名称查询 catalogId
            String catalogName = string[10];
            CatalogAppraisal appraisal = new CatalogAppraisal();
            appraisal.setName(catalogName);
            List<CatalogAppraisal> catalogAppraisals = catalogAppraisalService.selectCatalogAppraisalList(appraisal);
            if(catalogAppraisals.size() > 0){
                Integer catalogId = catalogAppraisals.get(0).getCatalogId();
                questions.setCatalogId(catalogId);
                questionsService.insertQuestions(questions);
            }else {
                return new ApiReturnObject("201", catalogName + " 目录名称无效，请修改后重新上传", "");
            }
        }
        return new ApiReturnObject("200", "操作成功", "");
    }


}
